<?php

/*
 * Author: thanhvd
 * Mail  : thanhvd89@gmail.com
 * Blog  : thanhvd89.wordpress.com
 * 
 */

class Bootstrap {
    
    private $data = array();
    
    function __construct() {
        if (!empty($_SESSION["tp_user"])) {
            $_SESSION["tp_cur_request"] = !empty($_REQUEST["r"]) ? $_REQUEST["r"] : "home/viewindex";
        } else {
            $_SESSION["tp_cur_request"] = "user/viewlogin";
        }
        $this->data = explode("/", $_SESSION["tp_cur_request"]);
    }
    
    function __destruct() {
        $this->data = array();
    }
    
    public function invoke() {
        $this->data = array_map("strtolower", $this->data);
        if (count($this->data) >= 2) {
            $class = ucfirst($this->data[0]);
            $controller = new $class();
            $method = "index";
            
            if (substr($this->data[1], 0, 2) == "do") {
                $method = "do".ucfirst(substr($this->data[1], 2));
                echo empty($this->data[2]) ? $controller->$method() : $controller->$method($this->data[2]);
            }
            
            if (substr($this->data[1], 0, 4) == "view") {
                $method = "view".ucfirst(substr($this->data[1], 4));
                $filepath = BASE_DIR."protected/views/".$this->data[0]."/".substr($this->data[1], 4).".html";
                try {
                    if (file_exists($filepath))
                        $controller->tpl = new XTemplate($filepath);
                    else
                        throw new Exception("FILE NOT FOUND!");
                } catch (Exception $e) {
                    echo "Message: " . $e->getMessage();
                }
                echo Layout::header();
                echo empty($this->data[2]) ? $controller->$method() : $controller->$method($this->data[2]);
                echo Layout::footer();
            }
            
        }
    }
            
}

?>
